﻿using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;

namespace ComicReader
{
    public static class Extensions
    {
        public static bool IsImage(this string fileName)
        {
            var retVal = false;
            var splitChar = ",";
            var strImageTypes = ComicReader.Properties.Settings.Default.ImageTypes;
            var imageExtensions = strImageTypes.Split(splitChar.ToCharArray());
            foreach (var ext in imageExtensions)
            {
                if (Path.GetExtension(fileName).ToLower().EndsWith(ext) != true) continue;
                retVal = true;
                break;
            }
            return retVal;
        }

        public static bool IsImage(this FileInfo fileInfo)
        {
            return fileInfo.Name.IsImage();
        }

        public static MemoryStream GetMemoryStream(this Stream s)
        {
            var ba = new byte[4096];
            var ms = new MemoryStream();
            var numRead = s.Read(ba, 0, ba.Length);
            while (numRead > 0)
            {
                ms.Write(ba, 0, numRead);
                numRead = s.Read(ba, 0, ba.Length);
            }
            ms.Position = 0;
            return ms;
        }

        public static BitmapImage GetBitmapImage(this Stream stream)
        {
            var positiom = stream.Position;
            var length = stream.Length;

            var memoryStream = stream.GetMemoryStream();
            var bitmap = new Bitmap(memoryStream); //make sure its valid
            memoryStream.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream; //could exception
            bitmapImage.EndInit();

            bitmap.Dispose();

            return bitmapImage;
        }
    }
}
